package edu.ynu.se.xiecheng.achitectureclass.controller.base;

import edu.ynu.se.xiecheng.achitectureclass.common.response.ApiResponse;
import edu.ynu.se.xiecheng.achitectureclass.service.base.BaseService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

@Slf4j
public abstract class BaseController<T, ID> {
    
    protected final BaseService<T, ID> service;
    
    protected BaseController(BaseService<T, ID> service) {
        this.service = service;
    }
    
    @GetMapping("/{id}")
    public ResponseEntity<ApiResponse<T>> findById(@PathVariable ID id) {
        return service.findById(id)
            .map(entity -> ResponseEntity.ok(ApiResponse.success(entity)))
            .orElse(ResponseEntity.notFound().build());
    }
    
    @PostMapping
    public ResponseEntity<ApiResponse<T>> save(@RequestBody T entity) {
        try {
            T savedEntity = service.save(entity);
            return ResponseEntity.ok(ApiResponse.success(savedEntity));
        } catch (Exception e) {
            log.error("保存实体失败", e);
            return ResponseEntity.badRequest()
                .body(ApiResponse.error(400, "保存失败: " + e.getMessage()));
        }
    }
    
    @DeleteMapping("/{id}")
    public ResponseEntity<ApiResponse<Void>> deleteById(@PathVariable ID id) {
        try {
            service.deleteById(id);
            return ResponseEntity.ok(ApiResponse.success(null));
        } catch (Exception e) {
            log.error("删除实体失败", e);
            return ResponseEntity.badRequest()
                .body(ApiResponse.error(400, "删除失败: " + e.getMessage()));
        }
    }
    
    protected ResponseEntity<ApiResponse<T>> handleException(Exception e) {
        log.error("操作失败", e);
        return ResponseEntity.internalServerError()
            .body(ApiResponse.error(500, "操作失败: " + e.getMessage()));
    }
} 